package com.zzj.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzj.base.Result;
import com.zzj.entity.Archive;
import com.zzj.entity.Hospital;
import com.zzj.entity.User;
import com.zzj.feign.ILikeApiFeign;
import com.zzj.model.dto.QueryListDTO;
import com.zzj.model.dto.hospital.HospitalCreateDTO;
import com.zzj.model.dto.hospital.HospitalUpdateDTO;
import com.zzj.service.IHospitalService;
import com.zzj.service.RedisService;
import com.zzj.utils.*;
import jakarta.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 医院 前端控制器
 * </p>
 *
 * @author zzj
 * @since 2023-03-23
 */
@RestController
@RequestMapping("/hospital")
public class HospitalController {
    @Resource
    private IHospitalService hospitalService;
    @Resource
    private RedisService redisService;

    @Resource
    private ILikeApiFeign likeApiFeign;

    @Transactional
    @PostMapping("list")
    public Result list(@RequestBody @Validated QueryListDTO in) {
        QueryWrapper<Hospital> queryWrapper = QueryUtil.paramsWrapper(in.getAndParams(), in.getOrParams(), in.getOrderParams());
        Page<Hospital> hospitalPage = new Page<>(in.getPageNo(), in.getPageSize());
        IPage<Hospital> hospitalIPage = hospitalService.getBaseMapper().selectPage(hospitalPage, queryWrapper);
        return Result.success(hospitalIPage);
    }


    @Transactional
    @PostMapping("create")
    public Result create(@RequestBody @Validated HospitalCreateDTO in) {
        Hospital hospital = JSONObject.parseObject(JSONObject.toJSONString(in), Hospital.class);

        Hospital serviceOne = hospitalService.getOne(Wrappers.<Hospital>lambdaQuery()
                        .eq(Hospital::getId, in.getHospital()),
                false);
        if (serviceOne != null) {
            return Result.error("该医院已存在");
        }
        hospitalService.save(hospital);
        return Result.success("创建成功");
    }

    @Transactional
    @PostMapping("update")
    public Result update(@RequestBody @Validated HospitalUpdateDTO in) {
        Hospital hospital = JSONObject.parseObject(JSONObject.toJSONString(in), Hospital.class);
        hospitalService.updateById(hospital);
        return Result.success("更新成功");
    }

    @Transactional
    @PostMapping("removeById")
    public Result removeById(@RequestParam int id) {
        hospitalService.removeById(id);
        return Result.success("删除成功");
    }


    @Transactional
    @PostMapping("parseWeb")
    public Result parseWeb(@RequestParam int page, @RequestParam int location) throws Exception {
        String url = "https://y.dxy.cn";
        List<com.zzj.model.entity.Hospital> hospitals = new HtmlParseUtil().hospitalParams(url, String.valueOf(page), String.valueOf(location));
        hospitals.forEach(hospital -> {
            try {
                Hospital h = JSONObject.parseObject(JSONObject.toJSONString(hospital), Hospital.class);
                hospitalService.save(h);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return Result.success();
    }


    @Transactional
    @PostMapping("id")
    public Result id(@RequestHeader(value = "Authorization") String token,
                     @RequestParam int id) {
        String username = JWTUtil.getUsername(token);
        String likeHospitalId = redisService.getLikeHospitalId(username);
        boolean is = Utils.stringIsContainStrSplit(likeHospitalId, String.valueOf(id), ",");

        Hospital one = hospitalService       .getOne(Wrappers.<Hospital>lambdaQuery()
                        .eq(Hospital::getId, id),
                false);
        one.setIsLike(is ? 1 : 0);
        return Result.success(one);
    }

    /**
     * 点赞 取消点赞
     * 未接入 推送
     *
     * @param token
     * @param id    文章ID
     * @return
     */
    @Transactional
    @PostMapping("like")
    public Result like(@RequestHeader(value = "Authorization") String token,
                       @RequestParam int id, @RequestParam String toUsername) {
        String username = JWTUtil.getUsername(token);
        String likeHospitalId = redisService.getLikeHospitalId(username);
        if (likeHospitalId != null) {
            List<String> likeHospitalIds = Utils.stringToList(likeHospitalId, ",");
            //取消点赞
            if (likeHospitalIds.contains(String.valueOf(id))) {
                hospitalService.dislike(id);
                likeHospitalId = likeHospitalId.replace(id + ",", "");
                likeApiFeign.remove(id, username);
            } else {
                //点赞
                hospitalService.like(id);
                likeHospitalId += id + ",";
                likeApiFeign.save(id, 4, username, toUsername);
            }
            redisService.setLikeHospitalId(username, likeHospitalId);
        } else {
            //点赞
            redisService.setLikeHospitalId(username, id + ",");
            hospitalService.like(id);
            likeApiFeign.save(id, 4, username, toUsername);
        }
        return Result.success("操作成功");
    }
}
